package com.micro.platform.user.rpc;

import com.micro.platform.starter.utils.BeanCopyUtil;
import com.micro.platform.user.dto.UserApisDTO;
import com.micro.platform.user.entity.*;
import com.micro.platform.user.service.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@DubboService
public class UserRpcServiceImpl implements UserRpcService{

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleFunctionService roleFunctionService;

    @Autowired
    private FunctionApiService functionApiService;

    @Override
    public UserApisDTO getUserApisByAccount(String account) {
        User user = userService.getUserByAccount(account);
        if(user == null){
            return null;
        }
        UserApisDTO userApisDTO = BeanCopyUtil.copyProperties(user, UserApisDTO::new);
        List<UserRole> userRoles = userRoleService.getUserRolesByUserId(userApisDTO.getId());
        List<Long> roleIds = userRoles.stream().map(UserRole::getRoleId).filter(Objects::nonNull).distinct().collect(Collectors.toList());
        if(CollectionUtils.isEmpty(roleIds)){
            return userApisDTO;
        }
        List<Role> roles = roleService.getRolesByIds(roleIds);
        List<String> roleCodes = roles.stream().map(Role::getCode).distinct().collect(Collectors.toList());
        userApisDTO.setRoleCodes(roleCodes);
        List<RoleFunction> roleFunctions = roleFunctionService.getRoleFunctionsByRoleIds(roleIds);
        List<Long> functionIds = roleFunctions.stream().map(RoleFunction::getFunctionId).collect(Collectors.toList());
        List<FunctionApi> functionApis = functionApiService.getFunctionApisByFunctionIds(functionIds);
        if(CollectionUtils.isEmpty(functionApis)){
            return userApisDTO;
        }
        List<String> apiUrls = functionApis.stream().map(FunctionApi::getApiUrl).distinct().collect(Collectors.toList());
        userApisDTO.setApis(apiUrls);
        return userApisDTO;
    }
}
